package com.wanhe.base.injector.module;

import android.app.Application;
import android.content.Context;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import io.reactivex.Flowable;
import io.reactivex.processors.FlowableProcessor;
import io.reactivex.processors.PublishProcessor;

/**
 * Created by cdj on 2017/6/26.
 */

@Module
public class BaseApplicationModule {

    private final Context mApplication;

    public BaseApplicationModule(Context application){
        this.mApplication = application;
    }

    @Provides
    @Singleton
    Context provideApplicationContext(){
        return this.mApplication.getApplicationContext();
    }

    @Provides
    @Singleton
    RxBus provideBus(){
        return new RxBus();
    }

    /**
     *
     * 将RxBus隐藏起来，防止外部直接创建BUS对象
     *
     * 这个Bus有背压处理
     *
     * @author 陈德基
     * @time 2017/6/26 11:15
     */
    public class RxBus {

        private final FlowableProcessor<Object> mBus;

        private RxBus() {
            // toSerialized method made bus thread safe
            mBus = PublishProcessor.create().toSerialized();
        }

        public void post(Object obj) {
            mBus.onNext(obj);
        }

        public <T> Flowable<T> toFlowable(Class<T> tClass) {
            return mBus.ofType(tClass);
        }

        public Flowable<Object> toFlowable() {
            return mBus;
        }

        public boolean hasSubscribers() {
            return mBus.hasSubscribers();
        }

    }

}
